#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  aging_test_case.py
#  
#  Copyright 2022 vicent-PC <vicent-PC@VICENT_PC>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  
import os
import time
import random
import traceback

import https_test
import websocket_test

target_ip = "192.168.1.103"
def sleep_round_ms():
    time_sleep = random.randint(1, 1000)/1000.0  #1us - 10s
    time_sleep_s = time_sleep * time_sleep * time_sleep * time_sleep #1us - 10s
    print("sleep: %.2f" % (time_sleep_s * 1000), "ms")
    time.sleep(time_sleep_s)

def http_aging_test():
    for i in range(1000*1000):
        print("Round", i)
        https_test.browseSimGet("http://"+target_ip+"/")
        sleep_round_ms()

# web socket test
def ws_aging_test():
    websocket_test.wsInit("ws://"+target_ip+"/")
    for i in range(1000*1000):
        print("Round", i)
        websocket_test.wsRequest("test")
        sleep_round_ms()

def web_mix_test(test_minutes):
    websocket_test.wsInit("ws://"+target_ip+"/")
    test_cnt = 1000 * 1000 * 1000
    start_time = time.time()
    for i in range(test_cnt):
        print("Round", i)
        https_test.browseSimGet("http://"+target_ip+"/")
        sleep_round_ms()
        websocket_test.wsRequest("test "+str(i))
        sleep_round_ms()
        if(time.time() - start_time > test_minutes * 60):
            break
    return True

def ping_test():
    os.system("ping " + target_ip);

def main(args):
    start_time = time.time()
    find_except = False
    try :
        ping_test()
        web_mix_test(10)
        #ws_aging_test()
        #http_aging_test()
    except:
        find_except = True
        traceback.print_exc()
    spend_time = time.time() - start_time
    if (find_except):
        print("\n\tSTS fail: abnormal interrupt. \ttime:%.2f" % (spend_time) ," s\n")
    else:
        print("\n\tSTS pass. \ttime:%.2f" % (spend_time)," s\n")
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
